import { useUserStore } from '@/stores/user'
import { getMAC } from '@/utils/getMAC';
export default class {
  constructor(options) {
    this.options = options
    this.connected = false
    this.reconnectInterval = 5000 // 重连间隔时间
    this.reconnectTimeoutID = null // 重连定时器 ID
    this.activityTimeoutID = null

    this.connect()
  }

  async connect() {
    const userStore = useUserStore()
    const macAddress = await getMAC();
    const url = new URL(this.options.url);
    url.searchParams.set('token', userStore.token);
    url.searchParams.set('plantcode', `${userStore.packageJs.plantcode}@${userStore.packageJs.plantcode2}`);
    url.searchParams.set('mac', macAddress);
    this.ws = new WebSocket(url);
    console.log(url);


    // 连接成功
    this.ws.onopen = () => {

      clearTimeout(this.activityTimeoutID)
      console.log('[WS] 连接成功')
      this.connected = true

      this.activityTimeoutID = setInterval(() => {

        if (this.ws != null) {
          this.send({ type: 'ping' })
        } else {
          this.activityTimeoutID = null
        }
      }, 30 * 1000)
    }

    // 连接关闭
    this.ws.onclose = e => {
      console.log('[WS] 连接关闭', e)
      this.connected = false
      this.reconnect()
    }

    // 连接失败
    this.ws.onerror = error => {
      console.error('[WS] 连接失败', error)
    }

    // 收到消息
    this.ws.onmessage = e => {

      const data = JSON.parse(e.data)
      // this.ws.close()
      // console.log('[WS] 收到消息', data)

      this.options?.onMessage && this.options?.onMessage(data)
    }
  }

  send(data) {
    this.ws.send(JSON.stringify(data))
  }

  // 重连
  reconnect() {
    if (this.ws != null) {
      if (this.reconnectTimeoutID) clearTimeout(this.reconnectTimeoutID)
      this.reconnectTimeoutID = setTimeout(() => {
        if (this.ws) {
          this.ws.close()
          this.ws = null
        }

        clearTimeout(this.activityTimeoutID)
        console.log('[WS] 重连中')
        // this.connect()
      }, this.reconnectInterval)
    }
  }

  // 销毁
  close() {
    console.log(this.ws);

    this.ws.close()
    this.ws = null

    clearTimeout(this.reconnectTimeoutID)
    clearTimeout(this.activityTimeoutID)
    this.reconnectTimeoutID = null
    this.activityTimeoutID = null
  }
}
